package initConfig

import sysAuth.*
import sysUtil.SysCommUtil
import xdTool.XdDataSource
import xdTool.XdWidget

/**
 * Created by Administrator on 2018-05-04.
 */
class InitAdmin {
    /**
     * 初始化系统数据
     * @return
     */
    def InitSysConfig(){
        SysDepartmentsInit()
        SysOrganizationInit()
        SysOperationsInit()
        SysParamsInit()
        SysUsersInit()
        SysFunctionsInit()
        SysRolesInit()
        SysViewCfgInit()
        XdDataSourceInit()
        SysNoticeInit()

        ///////////以上基础数据
        SysUserRolesInit()
        SysRoleRelaInit()
        SysFunOptInit()
        SysRoleRelaOperatInit()
        XdWidgetInit()
    }



    def XdWidgetInit(){
        if( XdWidget.countByClassFlag("xd-input") ==0 ){
            new XdWidget(
                    name: "文本框",
                    classFlag: "xd-input",
                    html: SysCommUtil.String2Clob("""
                <input type="text" name="" id="" class="xd-input layui-input" autocomplete="off" >
                """) ,
                    creator: SysInitData.SYS_ADMIN).save(flush: true)
        }

        if( XdWidget.countByClassFlag("xd-select") ==0 ){
            new XdWidget(
                    name: "下拉框",
                    classFlag: "xd-select",
                    html: SysCommUtil.String2Clob("""
                <select name="" id="" class="xd-select" xm-select-skin="default"  xm-select-height="36px" xm-select=""  xm-select-search="" xm-select-show-count="3" xm-select-radio="">
                <option value="0">否</option>
                <option value="1">是</option>
                </select>
                """) ,
                    creator: SysInitData.SYS_ADMIN).save(flush: true)
        }

        if( XdWidget.countByClassFlag("xd-date") ==0 ){
            new XdWidget(
                    name: "日期",
                    classFlag: "xd-date",
                    html: SysCommUtil.String2Clob("""
                <input type="text" id="" name="" class="xd-date layui-input" autocomplete="off">
                """) ,
                    creator: SysInitData.SYS_ADMIN).save(flush: true)

        }

        if( XdWidget.countByClassFlag("xd-panel-table") ==0 ){
            new XdWidget(
                    name: "数据表格",
                    classFlag: "xd-panel-table",
                    html: SysCommUtil.String2Clob("""
                <table class="layui-table" id="" lay-filter=""></table>
                """) ,
                    creator: SysInitData.SYS_ADMIN).save(flush: true)
        }


        def echarts = ["line":"折线图","bar":"柱状图","pie":"饼图","funnel":"漏斗图","gauge":"仪表盘","scatter":"散点图"]
        echarts.each {
            def classFlag = "xd-panel-echart-${it.key}"
            def instance = XdWidget.findByClassFlag(classFlag)
            if(!instance){
                new XdWidget(
                        name: "${it.value}",
                        classFlag: classFlag,
                        html: SysCommUtil.String2Clob("""<div id="" class="${classFlag}" style="width: 100%;height: 100%"></div>""") ,
                        creator: SysInitData.SYS_ADMIN).save(flush: true)
            }
        }
    }

    def SysRoleRelaOperatInit(){
        if(SysRoleRelaOperat.count == 0){
            def role = SysRoles.findByRoleNoAndRoleType(SysInitData.TEST_NAME,SysInitData.FUNC_ROLE)
            def sysRoleRela = SysRoleRela.findByRoleAndDataId(role,SysFunctions.findByFuncNo("SYS_USER").id)

            SysFunOpt.findAllByOperateNotInListAndFunction(SysOperations.findAllByOperateNoInList(['monitor','upLoad','detail']),SysFunctions.get(sysRoleRela.dataId) ).each {op ->
                new SysRoleRelaOperat(relaId : sysRoleRela.id,sysFunOptId : op.id).save(flush: true)
            }
        }
    }

    def SysFunOptInit(){
        if(SysFunOpt.count() == 0){

            SysOperations.findAllByOperateNoInList(['del','add','query','downLoad','upLoad','addAuth','edit']).each {
                new SysFunOpt(function: SysFunctions.findByFuncNo("SYS_USER"),operate: it).save(flush: true)
            }

            SysOperations.findAllByOperateNoInList([ 'add' ]).each {
                new SysFunOpt(function: SysFunctions.findByFuncNo("SYS_OPERATE"),operate: it).save(flush: true)
            }

            SysOperations.findAllByOperateNoInList([ 'query','test','add','downLoad','del' ]).each {
                new SysFunOpt(function: SysFunctions.findByFuncNo("SYS_SOURCE"),operate: it).save(flush: true)
            }

            SysOperations.findAllByOperateNoInList([ 'query' ,'add','downLoad','del','edit','copy' ]).each {
                new SysFunOpt(function: SysFunctions.findByFuncNo("SYS_PARAMS"),operate: it).save(flush: true)
            }

            //updateRead,updateReadAll,del,addPublicNoice,addPrivateNotice
            SysOperations.findAllByOperateNoInList([ 'updateRead' ,'updateReadAll','del','addPublicNotice' ]).each {
                new SysFunOpt(function: SysFunctions.findByFuncNo("SYS_NOTICE"),operate: it).save(flush: true)
            }

            SysOperations.findAllByOperateNoInList([ 'del','edit','add','query' ]).each {
                new SysFunOpt(function: SysFunctions.findByFuncNo("SYS_WIDGET1"),operate: it).save(flush: true)
            }
        }
    }

    def SysRoleRelaInit(){
        if(SysRoleRela.count ==0){
            def adminRole = SysRoles.findByRoleNo(SysInitData.ADMIN_FUNC_ROLE)
            SysRoles.list().each {
                new SysRoleRela(role: adminRole,dataId: it.id,roleType:SysInitData.FUNC_ROLE ).save(flush: true)
            }

            def testRole = SysRoles.findByRoleNoAndRoleType(SysInitData.TEST_NAME,SysInitData.FUNC_ROLE)
            SysFunctions.findAllByFuncNoInList(['SYS_SET','SYS_USER','SYS_ICON','SYS_FUNC']).each {
                new SysRoleRela(role: testRole,dataId: it.id,roleType:SysInitData.FUNC_ROLE ).save(flush: true)
            }

            testRole = SysRoles.findByRoleNoAndRoleType(SysInitData.TEST_NAME,SysInitData.DATA_ROLE)

            new SysRoleRela(role: testRole,dataId: SysOrganization.last().id,roleType:SysInitData.DATA_ROLE ).save(flush: true)

        }
    }

    def SysUserRolesInit(){
        if(SysUserRoles.count !=0){
            return
        }

        def adminUser = SysUsers.findAllByUserNo(SysInitData.SYS_ADMIN)
        SysRoles.findAllByRoleNoInList(SysInitData.AdminRole.keySet().toList()).each {
            new SysUserRoles(user: adminUser,role: it).save(flush: true)
        }

        def testUser = SysUsers.findByUserNo(SysInitData.TEST_NAME)
        SysRoles.findAllByRoleNo(SysInitData.TEST_NAME).each {
            new SysUserRoles(user: testUser,role: it).save(flush: true)
        }
    }

    def SysNoticeInit(){
        if(SysNotice.count() ==0){
            new SysNotice(title: "系统通知",content: "欢迎您使用XD后台管理系统",creator:SysInitData.SYS_ADMIN).save(flush: true)
        }
        Thread.start("Update Notice State..."){
            def sleepTime = 1000*60*60*2
            while (true){ //定时更新public消息状态
                try {
                    def list = SysNotice.findAllByStateAndType("1","0").id;
                    //println list
                    list.each {
                        def instance = SysNotice.get(it)
                        instance.updateState()
                    }
                }catch (Exception e){
                    new RuntimeException("Update Notice Error.........${e.getMessage()}")
                }
                print("Update Notice complete,waiting next.....")

                this.sleep(sleepTime)
            }
        }
    }

    def XdDataSourceInit(){
        if(XdDataSource.count()==0){
            new XdDataSource(
                    sourceName: "XD-PC-MySql-Test",
                    driverClassName: "com.mysql.jdbc.Driver",
                    username: "root",password: "xxd12345",state: "1",
                    url: "jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=true&characterEncoding=utf8",
                    creator: SysInitData.SYS_ADMIN).save(flush: true)
        }
    }
    def SysViewCfgInit(){
        if(SysViewCfg.count  !=0){
            return
        }

        new  SysViewCfg(
                webName:"XD-SYSADMIN",
                webIcon :"favicon.ico",
                sysName : "XD-SYSADMIN",
                sysLogo  : null,
                sysUrl:"http://localhost:8080/myWeb",
                uploadType  : "png|gif|jpg|jpeg|zip|rar",
                maxUpload  :'10200',
                creator:SysInitData.SYS_ADMIN,
                copyRight  : "Copyright ©${new Date().format("yyyy")} 徐向东 All Rights Reserved").save(flush: true)

    }

    def SysRolesInit(){
        if(SysRoles.count ==0){
            //add sys roles
            new SysRoles(roleNo:SysInitData.ADMIN_FUNC_ROLE ,roleName: SysInitData.AdminRole.get(SysInitData.ADMIN_FUNC_ROLE),roleType: SysInitData.FUNC_ROLE,creator:SysInitData.SYS_ADMIN).save(flush: true)
            new SysRoles(roleNo:SysInitData.ADMIN_DATA_ROLE,roleName: SysInitData.AdminRole.get(SysInitData.ADMIN_DATA_ROLE),roleType: SysInitData.DATA_ROLE,creator:SysInitData.SYS_ADMIN).save(flush: true)
            //add test roles
            new SysRoles(roleNo: SysInitData.TEST_NAME,roleName: SysInitData.TEST_NAME,roleType: SysInitData.FUNC_ROLE,creator:SysInitData.SYS_ADMIN).save(flush: true)
            new SysRoles(roleNo: SysInitData.TEST_NAME,roleName: SysInitData.TEST_NAME,roleType: SysInitData.DATA_ROLE,creator:SysInitData.SYS_ADMIN).save(flush: true)
        }
    }

    def SysFunctionsInit(){
        //系统默认菜单
        //系统一级菜单
        if(SysFunctions.count() ==0){

            def sysSet = new SysFunctions(funcNo: "SYS_SET",funcName: "系统管理",path:null,orderNum:0,parentId:null,icon:"layui-icon-set-sm" ,creator: SysInitData.SYS_ADMIN)
            sysSet.save(flush: true)

            def Grade2Function = [[funcNo:"SYS_USER",funcName:"用户管理",orderNum:1,parentId: sysSet.id,path:"reportAdmin/userList.html", icon:"layui-icon-user",creator: SysInitData.SYS_ADMIN],
                                  [funcNo:"SYS_FUNC",funcName:"功能管理",orderNum:2,parentId: sysSet.id,path:"reportAdmin/function.html", icon:"layui-icon-template",creator: SysInitData.SYS_ADMIN ],
                                  [funcNo:"SYS_DATA",funcName:"数据管理",orderNum:3,parentId: sysSet.id,path:"reportAdmin/data.html", icon:"layui-icon-table" ,creator: SysInitData.SYS_ADMIN],
                                  [funcNo:"SYS_DEPT",funcName:"部门管理",orderNum:3,parentId: sysSet.id,path:"reportAdmin/department.html", icon:"layui-icon-table" ,creator: SysInitData.SYS_ADMIN],
                                  [funcNo:"SYS_ROLE",funcName:"角色管理",orderNum:4,parentId: sysSet.id,path:"reportAdmin/roleList.html", icon:"layui-icon-templeate-1",creator: SysInitData.SYS_ADMIN ],
                                  [funcNo:"SYS_CFG",funcName:"系统配置",orderNum:7,parentId: sysSet.id,path:"reportAdmin/sysViewCfg.html", icon:"layui-icon-util",creator: SysInitData.SYS_ADMIN ],
                                  [funcNo:"SYS_OPERATE",funcName:"操作管理",orderNum:7,parentId: sysSet.id,path:"reportAdmin/operation.html", icon:"layui-icon-form" ,creator: SysInitData.SYS_ADMIN],
                                  [funcNo:"SYS_ICON",funcName:"图标管理",orderNum:8,parentId: null,path:"reportAdmin/unicode.html",icon:"layui-icon-face-smile",creator: SysInitData.SYS_ADMIN],
                                  [funcNo:"SYS_SOURCE",funcName:"数据源管理 ",orderNum:8,parentId: sysSet.id,path:"reportAdmin/dataSource.html",icon:"layui-icon-face-smile",creator: SysInitData.SYS_ADMIN],
                                  [funcNo:"SYS_NOTICE",funcName:"消息中心 ",orderNum:10,parentId: null,path:"reportAdmin/sysNotice.html",icon:"layui-icon-notice",creator: SysInitData.SYS_ADMIN],
                                  [funcNo:"SYS_PARAMS",funcName:"参数管理 ",orderNum:11,parentId: sysSet.id,path:"reportAdmin/sysParams.html",icon:"layui-icon-notice",creator: SysInitData.SYS_ADMIN]
            ]

            Grade2Function.each {
                new SysFunctions(funcNo:it.funcNo,funcName:it.funcName,orderNum:it.orderNum,parentId: it.parentId,path:it.path, icon:it.icon,creator: it.creator).save(flush: true)
            }
        }

    }

    /**
     * 初始数据
     * @return
     */
    def SysUsersInit(){
        if(SysUsers.count !=0){
            return
        }
        SysUsers userAdmin = SysUsers.newInstance()
        userAdmin.setUserNo(SysInitData.SYS_ADMIN)
        userAdmin.setUserName(SysInitData.SYS_ADMIN)
        userAdmin.setPassWord("1".encodeAsMD5())
        userAdmin.setCreator(SysInitData.SYS_ADMIN)
        userAdmin.setDeptId(SysDepartments.first().id)
        userAdmin.setOrgId(SysOrganization.first().id)
        userAdmin.save(flush: true)

        userAdmin = SysUsers.newInstance()
        userAdmin.setUserNo(SysInitData.TEST_NAME)
        userAdmin.setUserName(SysInitData.TEST_NAME)
        userAdmin.setPassWord("1".encodeAsMD5())
        userAdmin.setCreator(SysInitData.SYS_ADMIN)
        userAdmin.setDeptId(SysDepartments.last().id)
        userAdmin.setOrgId(SysOrganization.last().id)
        userAdmin.save(flush: true)
    }

    def SysParamsInit(){
        new SysParams(creator:SysInitData.SYS_ADMIN,paramsType: "USER_SEX",paramsDesc: "性别不可更改",value : "1",label:"男",state:"1",orderNum: 0 ).save(flush: true)
        new SysParams(creator:SysInitData.SYS_ADMIN,paramsType: "USER_SEX",paramsDesc: "性别不可更改",value: "0",label :"女",state:"1",orderNum: 0 ).save(flush: true)
        new SysParams(creator:SysInitData.SYS_ADMIN,paramsType: "USER_SEX",paramsDesc: "性别不可更改", value: "2",label:"其他",state:"1",orderNum: 0 ).save(flush: true)

        new SysParams(creator:SysInitData.SYS_ADMIN,paramsType: "BOOLEAN_FLAG",paramsDesc: "布尔不可更改", value: "1",label:"是",state:"1",orderNum: 0 ).save(flush: true)
        new SysParams(creator:SysInitData.SYS_ADMIN,paramsType: "BOOLEAN_FLAG",paramsDesc: "布尔不可更改", value: "0",label:"否",state:"1",orderNum: 0 ).save(flush: true)

        new SysParams(creator:SysInitData.SYS_ADMIN,paramsType: "EDUCATION",paramsDesc: "学历不可更改", value: "0",label:"本科",state:"1",orderNum: 0 ).save(flush: true)

        new SysParams(creator:SysInitData.SYS_ADMIN,paramsType: "POSITION",paramsDesc: "岗位不可更改", value: "0",label:"高级攻城师",state:"1",orderNum: 0 ).save(flush: true)
    }

    def SysOperationsInit(){
        if(SysOperations.count ==0){
            [detail:"详细",del:"删除",edit:"编辑",addAuth:"分配权限",test:"测试",copy:"复制",updateReadAll:"全部已读",
             updateRead:"标记已读"].each {key,value ->
                new SysOperations(operateNo:key,operateName:value,creator: SysInitData.SYS_ADMIN ,type: SysInitData.ROW_BUTTON).save(flush: true)
            }

            [save:"保存",add:"新增",downLoad:"下载",upLoad:"导入",query:"查询",monitor:"定时刷新",addPublicNotice:"发布公告"].each {key,value ->
                new SysOperations(operateNo:key,operateName:value,creator: SysInitData.SYS_ADMIN ,type: SysInitData.FORM_BUTTON).save(flush: true)
            }

        }
    }
    def SysOrganizationInit(){
        if(SysOrganization.count() ==0){
            def root = new SysOrganization (orgNo: "root",name: "大中华集团",creator: SysInitData.SYS_ADMIN)
            root.save(flush: true)
            def child = new SysOrganization(orgNo: 'org1',name: "陕西分公司",creator: SysInitData.SYS_ADMIN,parentId: root.id)
            child.save(flush: true)
            child = new SysOrganization(orgNo: 'org2',name: "上海办事处",creator: SysInitData.SYS_ADMIN,parentId: root.id)
            child.save(flush: true)
            child = new SysOrganization(orgNo: 'org3',name: "华东大区",creator: SysInitData.SYS_ADMIN,parentId: root.id)
            child.save(flush: true)
        }

    }
    def SysDepartmentsInit(){
        if(SysDepartments.count !=0){
            return
        }
        def root = new SysDepartments(deptNo: "dept01",name: "集团",creator: SysInitData.SYS_ADMIN,state:"1")
        root.save(flush: true)

        root = new SysDepartments(deptNo: "dept02",name: "陕西控股",creator: SysInitData.SYS_ADMIN,parentId:root.id,state:"1" )
        root.save(flush: true)
        new SysDepartments(deptNo: "dept03",name: "西安分公司",creator: SysInitData.SYS_ADMIN,parentId: root.id,state:"0").save(flush: true)
    }
}
